//封装了网络接口的文件，为servercalc.hpp和clientcalc.cc提供接口
#pragma once
#include "log.hpp"

#include <iostream>
#include <unistd.h>
#include <cstring>


#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

enum
{
    socketerr = 1,
    binderr,
    listenerr,
    connecterr
};

const int backlog = 10;

class Sock
{
public:
    Sock(){}
    ~Sock(){}
public:
    void Socket()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(_sockfd < 0)
        {
            LOG(Fatal, "socket error");
            exit(socketerr);
        }
        LOG(Info, "socket success");

    }
    void Bind(const uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;

        int ret = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        if(ret < 0)
        {
            LOG(Fatal, "bind error");
            exit(binderr);
        }
        LOG(Info, "bind success");
    }
    void Listen()
    {
        int ret = listen(_sockfd, backlog);
        if(ret < 0)
        {
            LOG(Fatal, "listen error");
            exit(listenerr);
        }
        LOG(Info, "listen...");
    }
    int Accept(std::string* clientip, uint16_t* clientport)
    {
        struct sockaddr_in client;
        memset(&client, 0, sizeof(client));
        // client.sin_family = AF_INET;
        // client.sin_port = ntohs(port);
        // inet_aton(clientip.c_str(), &client.sin_addr);
        
        socklen_t len = sizeof(client);
        int sockfd = accept(_sockfd, (struct sockaddr*)&client, &len);
        if(sockfd < 0)
        {
            LOG(Waring, "accept error");
            return -1;
        }

        char ipbuf[32];
        *clientip = inet_ntop(AF_INET, &client.sin_addr, ipbuf, sizeof(ipbuf));
        *clientport = ntohs(client.sin_port);
        std::cout << "[Info][get a new link...][clientip:" << *clientip << " clientport:" << *clientport <<"]" << std::endl;

        return sockfd;
    }
    void Connect(const std::string& serverip, const uint16_t serverport)
    {
        struct sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_port = htons(serverport);
        inet_aton(serverip.c_str(), &server.sin_addr);

        int ret = connect(_sockfd, (struct sockaddr*)&server, sizeof(server));
        if(ret < 0)
        {
            LOG(Fatal, "connect error");
            exit(connecterr);
        }
        std::cout << "[Info][connect server success][serverip:" << serverip << " serverport:" << serverport <<"]" << std::endl;
    }
    void Close()
    {
        if(_sockfd > 0) close(_sockfd);
    }
public:
    int _sockfd;
};